// src/utils/localStorage.js
const PREFIX = 'racing_car_rental_';

export const setItem = (key, value) => {
  try {
    localStorage.setItem(`${PREFIX}${key}`, value);
  } catch (error) {
    console.error(`Error saving to localStorage: ${error}`);
  }
};

export const getItem = (key) => {
  try {
    return localStorage.getItem(`${PREFIX}${key}`);
  } catch (error) {
    console.error(`Error reading from localStorage: ${error}`);
    return null;
  }
};

export const removeItem = (key) => {
  try {
    localStorage.removeItem(`${PREFIX}${key}`);
  } catch (error) {
    console.error(`Error removing from localStorage: ${error}`);
  }
};

export const clearAll = () => {
  try {
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith(PREFIX)) {
        localStorage.removeItem(key);
      }
    });
  } catch (error) {
    console.error(`Error clearing localStorage: ${error}`);
  }
};

// Initial data setup
export const initializeData = () => {
  if (!getItem('initialized')) {
    // Sample tracks data
    setItem('tracks', JSON.stringify([
      {
        id: 1,
        name: 'Shanghai International Circuit',
        description: 'F1赛道，全长5.451公里',
        location: '上海市嘉定区',
        image: '/assets/images/tracks/shanghai.jpg'
      }
    ]));

    // Sample vehicles data
    setItem('vehicles', JSON.stringify([
      {
        id: 1,
        name: 'Ferrari 488 GT3',
        description: '赛道专用GT3赛车',
        price: 9999,
        image: '/assets/images/vehicles/ferrari.jpg'
      }
    ]));

    setItem('initialized', 'true');
  }
};